<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Distributor extends BaseModel
{
    protected $fillable = [
    	'name',
	    'mobile',
	    'promo_code',
	    'promo_code_url',
	    'distributor_level_id',
	    'total_amount',
	    'usable_amount',
	    'frozen_amount',
	    'used_amount'
    ];
    
    public function delete()
    {
    	// 删除分销员时 终止关联
    	$user = User::where('distributor_id', $this->id)->first();
    	
    	if (!is_null($user)) {
    	    $user->distributor_id = 0;
    	    $user->save();
	    }

	    return parent::delete();
    }
	
	// 关联分销等级
	public function distributorLevel()
	{
		return $this->belongsTo(DistributorLevel::class);
	}
	
	// 关联用户表
	public function user()
	{
		return $this->hasOne(User::class);
	}
    
    // 总佣金 可用佣金 冻结佣金 已提现佣金 修改器 获取器组
    public function setTotalAmountAttribute($value)
    {
        $this->attributes['total_amount'] = $value * 100;
    }
    
    public function getTotalAmountAttribute($value)
    {
        return $value / 100;
    }
    
    public function setUsableAmountAttribute($value)
    {
        $this->attributes['usable_amount'] = $value * 100;
    }
    
    public function getUsableAmountAttribute($value)
    {
        return $value / 100;
    }
    public function setFrozenAmountAttribute($value)
    {
        $this->attributes['frozen_amount'] = $value * 100;
    }
    
    public function getFrozenAmountAttribute($value)
    {
        return $value / 100;
    }
    
    public function setUsedAmountAttribute($value)
    {
        $this->attributes['used_amount'] = $value * 100;
    }
    
    public function getUsedAmountAttribute($value)
    {
        return $value / 100;
    }
}
